package com.wjjun.base.ui.fragment

import android.view.LayoutInflater
import android.view.View
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.lifecycleScope
import com.wjjun.base.BR
import com.wjjun.base.ui.listener.IViewListener
import com.wjjun.base.ui.viewmodel.BaseActivityViewModel
import com.wjjun.base.ui.viewmodel.BaseWindowViewModel
import com.wjjun.base.utils.ViewModelFactory
import kotlinx.coroutines.launch

/**
 * 基础的绑定Fragment
 * author : wangjunjun
 * date   : 2022/7/1
 * desc   :
 */
open abstract class BaseBindingFragment<VM : BaseWindowViewModel, VD : ViewDataBinding> : BaseFragment(), IViewListener {

    lateinit var viewModel: VM

    lateinit var viewDataBinding: VD

    override fun initViews(inflater: LayoutInflater): View {
        buildViewModel()
        buildViewBinding(inflater)
        bindViewModel()
        return viewDataBinding.root
    }

    override fun initData() {
        lifecycleScope.launch() {
            fetchData()
        }
    }

    abstract suspend fun fetchData()

    open fun buildViewModel() {
        //从ViewModelProvider中获取的ViewModel可以实现hilt注入，且会在Activity重启时还原
        viewModel = ViewModelFactory.createViewModel(
                this,
                this.javaClass,
                BaseWindowViewModel::class.java
        )
    }

    open fun buildViewBinding(inflater: LayoutInflater) {
        var layoutId = getLayoutId()
        if (layoutId == 0) {
            layoutId = viewModel.getLayoutId()
        }
        viewDataBinding = DataBindingUtil.inflate(inflater, layoutId, null, false)
        viewDataBinding.lifecycleOwner = viewLifecycleOwner
    }

    @LayoutRes
    open fun getLayoutId(): Int {
        return 0
    }

    open fun bindViewModel() {
        viewDataBinding.setVariable(BR.viewModel, viewModel)
        viewDataBinding.setVariable(BR.listener, this)
    }
}